

package com.hazelcast.client.impl.clientside;

import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.security.RealmConfig;
import com.hazelcast.security.RealmConfigCallback;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

/**
 * {@link CallbackHandler} implementation which can be used on client side to access system internals.
 */
public class ClientCallbackHandler implements CallbackHandler {

    private final ClientConfig clientConfig;

    public ClientCallbackHandler(ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    @Override
    public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
        for (Callback cb : callbacks) {
            handleCallback(cb);
        }
    }

    protected void handleCallback(Callback cb) throws UnsupportedCallbackException {
        if (cb instanceof RealmConfigCallback realmCb) {
            RealmConfig realmCfg = null;
            if (clientConfig != null && clientConfig.getSecurityConfig() != null) {
                realmCfg = clientConfig.getSecurityConfig().getRealmConfig(realmCb.getRealmName());
            }
            realmCb.setRealmConfig(realmCfg);
        } else {
            throw new UnsupportedCallbackException(cb);
        }
    }
}
